extends Node2D

var id = 0
var hasData = false
var _iconSize:Vector2
var _iconTexture:Texture
signal mouse_click

# Called when the node enters the scene tree for the first time.
func _ready():
	_iconSize = $icon.get_rect().size
	_iconTexture = $icon.texture
	pass # Replace with function body.
	
func setDefault():
	var icon = $icon
	icon.texture = _iconTexture
	icon.scale = Vector2(1, 1)
	$title.text = "NO DATA"
	$gameTime.text = "游戏时间: 00:00:00"
	$saveTime.text = "保存时间: 0000/00/00"
	hasData = false
	
func setIndex(v : int):
	setDefault()
	id = v
	$number.text = "NO.{v}".format({
		"v": v+1
	})
	var save_path = "user://save_data_{number}".format({
		"number": v
	})
	var png_file = save_path + '/' + 'screenshot.png'
	if File.new().file_exists(png_file):
		var image = Image.new()
		image.load(png_file)
		var icon = $icon
		var texture = ImageTexture.new()
		texture.create_from_image(image)
		icon.texture = texture
		icon.scale = Vector2(_iconSize.x / image.get_size().x, _iconSize.y / image.get_size().y)
	var info = Model.getSaveDataInfo(v)
	if !info.has("game_name") or info.game_name != Config.game_name:
		return
	if info.has("save_flag") and info.save_flag == "godot-lite2d":
		hasData = true
		if info.has('game_chapter'):
			$title.text = info.game_chapter
		if info.has('play_time'):
			$gameTime.text = "游戏时间: {time}".format({
				"time": _getGameTime(info.play_time)
			})
		if info.has('save_time'):
			var save_time = OS.get_datetime_from_unix_time(info.save_time)
			$saveTime.text = "保存时间: {year}/{month}/{day} {hour}:{minute}:{second}".format({
				"year": save_time.year,
				"month": _getDoubleNumber(save_time.month),
				"day": _getDoubleNumber(save_time.day),
				"hour": _getDoubleNumber((save_time.hour + 8) % 24),
				"minute": _getDoubleNumber(save_time.minute),
				"second": _getDoubleNumber(save_time.second)
			})
		
func _getGameTime(seconds : int):
	var _minute = 60.0
	var _hour = _minute * 60.0
	var hour = int(floor(seconds / _hour))
	var minute = int(floor(seconds / _minute))
	var second = seconds % 60
	return "{hour}:{minute}:{second}".format({
		"hour": _getDoubleNumber(hour),
		"minute": _getDoubleNumber(minute),
		"second": _getDoubleNumber(second)
	})
	
func _getDoubleNumber(v : int):
	if v < 10:
		return "0{num}".format({
			"num": v
		})
	return v

func _on_button_button_down():
	if !Model.save.isSaveMode() && !hasData:
		return
	get_node("mask").visible = true
	pass # Replace with function body.

func _on_button_pressed():
	if !Model.save.isSaveMode() && !hasData:
		return
	get_node("mask").visible = false
	emit_signal("mouse_click", id)
	pass # Replace with function body.

func _on_button_gui_input(event):
	var visible = get_node("mask").visible
	if visible && event is InputEventMouseMotion:
		var size = get_node("button").rect_size
		var pos = event.position
		if pos.x < 0 || pos.x > size.x || pos.y < 0 || pos.y > size.y:
			get_node("mask").visible = false
			return
